package com.sunnyweather.android.logic

import androidx.lifecycle.liveData
import com.sunnyweather.android.logic.model.City
import com.sunnyweather.android.logic.network.SunnyWeatherNetwork
import kotlinx.coroutines.Dispatchers
import java.lang.Exception
import java.lang.RuntimeException

object Repository {
    fun searchCities(query: String) = liveData(Dispatchers.IO) {
        val result = try {
            val cityResponse = SunnyWeatherNetwork.searchCities(query)
            if (cityResponse.status == 0) {
                val cities = cityResponse.results
                Result.success(cities)
            } else {
                Result.failure(RuntimeException("response status is ${cityResponse.status}"))
            }
        } catch (e: Exception) {
            Result.failure<City>(e)
        }
        emit(result)
    }
}